<template>
    <div ref="editor"></div>
</template>
<script lang="ts">
import Vue from 'vue'
import Editor from 'wangeditor'
import { imageUpdate } from '@/apis/course'
export default Vue.extend({
  name: 'text-editor',
  props: {
    value: {
      type: String
    }
  },
  data() {
    return {
      editor: {} as Editor
    }
  },
  mounted() {
    this.initEditor()
  },
  methods: {
    initEditor() {
      const dom = this.$refs.editor as Element
      this.editor = new Editor(dom)
      // 自定义上传需要放在create之前
      this.editor.config.customUploadImg = async function(resultFiles: any, insertImgFn: any) {
        console.log(resultFiles)
        const form = new FormData()
        form.append('file', resultFiles[0])
        const { data } = await imageUpdate(form)
        if (data.code === '000000') {
          // 上传图片，返回结果，将图片插入到编辑器中
          insertImgFn(data.data.name)
        }
        // resultFiles 是 input 中选中的文件列表
        // insertImgFn 是获取图片 url 后，插入到编辑器的方法
      }
      this.editor.create()

      this.editor.config.onchange = (newHtml: string) => {
        this.$emit('input', newHtml)
      }
    }
  },
  watch: {
    value: function(newVal) {
      console.log(newVal)
      this.editor.txt.html(this.value)
    }
  }
})
</script>
<style lang="scss" scoped>

</style>
